package com.imooc.listener;

import com.imooc.entity.User;
import com.imooc.util.SessionUtil;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@WebListener
public class MyServletRequestListener implements ServletRequestListener{

    private ArrayList<User> userList; //在线用户List

    @Override
    public void requestDestroyed(ServletRequestEvent event) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent event) {

        userList = (ArrayList<User>) event.getServletContext().getAttribute("userList");

        if (userList == null){
            userList = new ArrayList<User>();
        }

        HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
        String sesstionId = request.getSession().getId();

        if (SessionUtil.getUserBySessionId(userList, sesstionId) == null){
            User user = new User();
            user.setSessionId(sesstionId);
            user.setFirstTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            user.setIp(request.getRemoteAddr());
            userList.add(user);
        }
        event.getServletRequest().setAttribute("userList",userList);
    }


}
